#include "playscene.h"
#include "config.h"
#include <QPainter>
#include <QPixmap>
#include <QApplication>
#include <QDebug>
#include <ctime>


PlayScene::PlayScene(QWidget *parent)
    : QWidget{parent}
{
    //初始化窗口大小
    setFixedSize(GAME_WIDTH,GAME_HEIGTH);

    //设置窗口标题
    setWindowTitle(GAME_TITLE);

    //加载图标
    setWindowIcon(QIcon(GAME_ICON));

    //定时器设置
    m_Timer.setInterval(GAME_RATE);

    playGame();

    //初始化人物坐标
    m_hero.m_X = 100;
    m_hero.m_Y = m_ground.grounds[0].m_Y - m_hero.m_Rect.height()+5;
    m_hero.m_Rect.moveTo(m_hero.m_X,m_hero.m_Y);

    //初始化金币计数
    m_recorder = 0;

    //随机数种子
    srand((unsigned int)time(NULL));

    //初始化吃到的金币数
    Coin_Score = 0;




}

void PlayScene::playGame()
{
    //启动定时器
    m_Timer.start();

    //监听定时器发送的信号
    connect(&m_Timer,&QTimer::timeout,[=](){
        //金币出场
        coinToScene();
        //更新游戏中的元素坐标
        updatePosition();
        //绘制到屏幕中
        update();

        //显示当前金币数
        Coin_Label->setParent(this);
        QString str = QString("Coin: %1").arg(Coin_Score);
        Coin_Label->setText(str);
        QFont font("华文新魏",20);
        Coin_Label->setFont(font);
        //设置标签大小、位置
        Coin_Label->setGeometry(QRect(30,30,this->width(),30));
        //设置属性
        Coin_Label->setAttribute(Qt::WA_TransparentForMouseEvents);
    });
}

void PlayScene::updatePosition()
{
    //更新地图的坐标
    m_ground.updatePositions();

    //更新人物
    checkCollisions();

    handleHorizontalMovement();

    handleVerticalMovement();

    m_hero.m_X += m_hero.m_Vx;
    m_hero.m_Y += m_hero.m_Vy;
    m_hero.m_Rect.moveTo(m_hero.m_X,m_hero.m_Y);
    qDebug()<<m_hero.m_X<<" "<<m_hero.m_Y;

    //金币出场
    for(int i=0;i<COIN_NUM;i++)
    {
        if(m_coins[i].m_Free == false)
        {
            m_coins[i].updatePosition();
        }
    }

}

void PlayScene::paintEvent(QPaintEvent *)
{
    //创建画家对象
    QPainter painter(this);
    //创建QPixmap对象
    QPixmap pix;
    pix.load(PLAY_SCENE);

    //绘制背景
    painter.drawPixmap(0,0,this->width(),this->height(),pix);

    //绘制特尔克西
    painter.drawPixmap(m_hero.m_X,m_hero.m_Y,m_hero.m_Hero);

    //绘制地面块
    for(int i=0;i<17;i++)
    {
        //补充第十六块和第一块之间的缝隙
        int drawWidth = m_ground.grounds[i].m_Map.width();
        if(i==16)
        {
            drawWidth += 4;
        }
        painter.drawPixmap(m_ground.grounds[i].m_X,m_ground.grounds[i].m_Y,
                           drawWidth,m_ground.grounds[i].m_Map.height(),
                           m_ground.grounds[i].m_Map);
    }

    //绘制金币
    for(int i=0;i<COIN_NUM;i++)
    {
        if(m_coins[i].m_Free == false)
        {
            painter.drawPixmap(m_coins[i].m_X,m_coins[i].m_Y,m_coins[i].m_Coin);
        }
    }

}

void PlayScene::coinToScene()
{
    m_recorder ++;
    //未达到出场间隔，直接return
    if(m_recorder < COIN_INTERVAL)
    {
        return;
    }

    m_recorder = 0;
    for(int i=0;i<COIN_NUM;i++)
    {
        //如果是空闲金币，出场
        if(m_coins[i].m_Free)
        {
            m_coins[i].m_Free = false;

            //坐标
            m_coins[i].m_X = GAME_WIDTH + m_coins[i].m_Rect.height();
            m_coins[i].m_Y = rand()%(GAME_HEIGTH - m_coins[i].m_Rect.height());
            break;
        }
    }
}
void PlayScene::keyPressEvent(QKeyEvent *event)
{
    switch(event->key())
    {
    case Qt::Key_D:
    {
        m_hero.m_Hero.load(HERO_PATH);
        m_hero.m_WantToMoveRight = true;
        break;
    }
    case Qt::Key_A:
    {
        m_hero.m_Hero.load(HERO_LEFT_PATH);
        m_hero.m_WantToMoveLeft = true;
        break;
    }
    case Qt::Key_W:
    {
        if(m_hero.m_IsOnGround)
        {
            m_hero.m_Vy = m_hero.m_JumpForce;
            m_hero.m_IsOnGround = false;
            m_hero.m_JumpCount = 1;
        }
        else if(m_hero.m_CanDoubleJump && m_hero.m_JumpCount<m_hero.m_MaxJump)
        {
            //二段跳
            m_hero.m_Vy = m_hero.m_JumpForce * 0.9;
            m_hero.m_JumpCount++;
            m_hero.m_CanDoubleJump = false;
        }
        break;
    }
    default:
        break;
    }
}

void PlayScene::keyReleaseEvent(QKeyEvent *event)
{
    switch(event->key())
    {
    case Qt::Key_D:
    {
        m_hero.m_WantToMoveRight = false;
        break;
    }
    case Qt::Key_A:
    {
        m_hero.m_WantToMoveLeft = false;
        break;
    }
    }
}

void PlayScene::handleHorizontalMovement()
{
    double controlFactor = m_hero.m_IsOnGround ? 1.0 : m_hero.m_AirControl;

    if(m_hero.m_WantToMoveRight && !m_hero.m_WantToMoveLeft)
    {
        //向右加速
        double temp = m_hero.m_Vx + m_hero.m_Acceleration*controlFactor;
        m_hero.m_Vx = (temp < m_hero.m_MaxSpeed) ? temp : m_hero.m_MaxSpeed;
    }
    else if(!m_hero.m_WantToMoveRight && m_hero.m_WantToMoveLeft)
    {
        //向左加速
        double temp = m_hero.m_Vx - m_hero.m_Acceleration*controlFactor;
        m_hero.m_Vx = (temp > m_hero.m_MaxSpeed) ? m_hero.m_MaxSpeed : temp;
    }
    else
    {
        //没有按键时减速
        m_hero.m_Vx *=m_hero.m_Deceleration;
        if(qAbs(m_hero.m_Vx)<0.1)
        {
            m_hero.m_Vx = 0;
        }
    }
}

void PlayScene::handleVerticalMovement()
{
    if(!m_hero.m_IsOnGround)
    {
        //应用重力
        m_hero.m_Vy += m_hero.m_G;

        if(m_hero.m_Vy >=15.0)
        {
            m_hero.m_Vy = 15.0;
        }
    }
}

void PlayScene::checkCollisions()
{
    m_hero.m_Rect.moveTo(m_hero.m_X,m_hero.m_Y);
    //检查地面碰撞
    for(int i=0;i<17;i++)
    {
        if(m_hero.m_Rect.intersects(m_ground.grounds[i].m_Rect))
        {
            //计算碰撞深度
            double penetrate = (m_hero.m_Y + m_hero.m_Rect.height()) - m_ground.grounds[i].m_Y;

            //从上碰撞
            if(m_hero.m_Vy > 0 && penetrate >0 && penetrate<=15)
            {
                m_hero.m_Y = m_ground.grounds[i].m_Y - m_hero.m_Rect.height()+5;
                m_hero.m_Vy = 0;
                m_hero.m_IsOnGround = true;
                m_hero.m_Rect.moveTo(m_hero.m_X,m_hero.m_Y);
            }
        }
    }
    //边界检查
    if(m_hero.m_X < 0)
    {
        m_hero.m_X = 0;
        m_hero.m_Vx = 0;
    }
    else if(m_hero.m_X > this->width()-m_hero.m_Rect.width())
    {
        m_hero.m_X = this->width()-m_hero.m_Rect.width();
        m_hero.m_Vx = 0;
    }

    if(m_hero.m_Y <= 0)
    {
        m_hero.m_Y = 0;
    }
    //二段跳
    if(m_hero.m_IsOnGround)
    {
        m_hero.m_JumpCount = 0;
        m_hero.m_CanDoubleJump = true;
    }

    //特尔克西和金币碰撞
    for(int i=0;i<COIN_NUM;i++)
    {
        if(m_coins[i].m_Free)
        {
            continue;
        }
        if(m_coins[i].m_Rect.intersects(m_hero.m_Rect))
        {
            m_coins[i].m_Free = true;
            Coin_Score++;
        }
    }
}
